﻿using Klear.Library.Helpers;
using Klear.Library.Models;

namespace Klear.Library.Services;

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http.Headers;
using Newtonsoft.Json;

public class FormatInformation : IFormatInformation
{
    public async Task<IncomeAndExpensesModel> SendPrompt(string billContent)
    {
        Console.WriteLine("等待生成JSON...");
        string json=MessageStorage.GetAccessMsg(billContent);
        using (var client = new HttpClient())
        {
            var request = new HttpRequestMessage(HttpMethod.Post, AccessKeyStorage.MODEL_URL);
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", AccessKeyStorage.API_KEY);
            var settings = new JsonSerializerSettings
            {
                Formatting = Formatting.Indented,
                StringEscapeHandling = StringEscapeHandling.EscapeNonAscii
            };
            PromptRequest message = new PromptRequest(json);
            string requestStr = JsonConvert.SerializeObject(message, settings).ToLower();
            request.Content = new StringContent(requestStr, Encoding.UTF8, "application/json");

            var response = await client.SendAsync(request);

            if (response.IsSuccessStatusCode)
            {
                string responseMessage = await response.Content.ReadAsStringAsync();
                IncomeAndExpensesModel res= JsonHelper.JsonToIncomeAndExpenses(responseMessage);
                if (res is null)
                {
                    Console.WriteLine("Inner JSON text is null or empty.");
                    return null;
                }

                return res;
            }
            else
            {
                Console.WriteLine("Inner JSON text is null or empty.");
                return null;
            }
            return null;
        }
    }
}
